package com.itheima.dubbo.mongodb.impl;


import cn.hutool.core.collection.CollUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.commons.model.mongo.Album;
import com.itheima.commons.model.mongo.Publish;
import com.itheima.dubbo.interfaces.AlbumApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class AlbumApiImpl implements AlbumApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存圈子信息到自己的相册表
     *
     * @param album
     * @param userid
     */
    @Override
    public void saveAlbum(Album album, Long userid) {
        mongoTemplate.save(album, "quanzi_album_" + userid);
    }

    /**
     * 查询自己的相册表
     *
     * @param page
     * @param pagesize
     * @param userId   要查询的那个用户的ID
     * @return
     */
    @Override
    public List<Publish> findMovementsByUserId(Integer page, Integer pagesize, Long userId) {
        // 先查询这个人的相册表
        List<Album> albumList = mongoTemplate.find(new Query()
                        .with(Sort.by(Sort.Order.desc("created")))
                        .with(PageRequest.of(page - 1, pagesize))
                , Album.class, "quanzi_album_" + userId);
        // 提取圈子的ID
        List<Object> publishIds = CollUtil.getFieldValues(albumList, "publishId");
        // 再根据圈子的id查询圈子的发布表
        return mongoTemplate.find(Query.query(Criteria.where("id").in(publishIds)), Publish.class);
    }
}
